package com.longrise.android.byjk.plugins.productfeerate;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.permission.PermissionUtil;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.fileuploader.BBOkHttp;
import com.longrise.fileuploader.response.IResponseHandler;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by callxkj on 2017/5/26.
 * 文件上传 上传产品费率 文档或者图片
 */

public class UploadProductfeerateActivity extends BaseActivity<UploadProductfeeratePresenter>
        implements UploadProductfeerateContract.View, View.OnClickListener {

    private static final String TAG = "UploadProductfeerateActivity";
    private TextView mTv_filename;
    private EditText mEtcpmc;
    private LinearLayout mLlfile;
    private LinearLayout mLlgallery;
    private LinearLayout mLlcamera;
    private static final int SELECT_FILE_REQ = 100;
    private static final int SELECT_GALLERY_REQ = 101;
    private static final int SELECT_CAMERA_REQ = 102;
    private Toolbar mToolbar;
    private ArrayList<ImageItem> mImageList = new ArrayList<>(); //存储的是未压缩的照片地址
    private GridView mGv;
    private ProductfeeGridAdapter mAdapter;
    private RelativeLayout mRlfile;
    private String mFilePath;
    private Button mBtconfirm;
    private int mProgress = -1;
    private ImageView mIvfile;
    private ImageView mIvgallery;
    private ImageView mIvcamera;
    private int mProductNumber;
    private String mUploadProductname;
    private ImagePicker mImagePicker;
    private TextView mTvytj;
    private List<String> mZipImageList = new ArrayList<>(); //压缩后的图片地址
    private final int PIC_NUM = 12; //最多上传图片的张数
    private TextView mTvwd;
    private TextView mTvzp;
    private TextView mTvpz;
    private boolean  mSuccessFlag;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_uploadproductfeerate;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle(R.string.fee_wjsc);
        mEtcpmc = (EditText) findViewById(R.id.uploadproductfee_et);
        mRlfile = (RelativeLayout) findViewById(R.id.ploadproductfee_file_rl);
        mTv_filename = (TextView) findViewById(R.id.uploadproductfee_filename_tv);
        mLlfile = (LinearLayout) findViewById(R.id.uploadproductfee_file_ll);
        mLlgallery = (LinearLayout) findViewById(R.id.uploadproductfee_gallery_ll);
        mLlcamera = (LinearLayout) findViewById(R.id.uploadproductfee_camera_ll);
        mIvfile = (ImageView) findViewById(R.id.uploadproductfee_file_iv);
        mIvgallery = (ImageView) findViewById(R.id.uploadproductfee_gallery_iv);
        mIvcamera = (ImageView) findViewById(R.id.uploadproductfee_camera_iv);
        mGv = (GridView) findViewById(R.id.uploadproductfee_gv);
        mBtconfirm = (Button) findViewById(R.id.uploadproductfee_upload_tv);
        mTvytj = (TextView) findViewById(R.id.ploadproductfee_ytj);
        mTvwd = (TextView) findViewById(R.id.uploadproductfee_file_tv);
        mTvzp = (TextView) findViewById(R.id.uploadproductfee_gallery_tv);
        mTvpz = (TextView) findViewById(R.id.uploadproductfee_camera_tv);
        setConfrimButton(false);
        setDocumentEnable(true, true);
        initAdapter();
        initEvent();
        initProductName();
        initImagePicker();
    }

    private void initAdapter() {
        mAdapter = new ProductfeeGridAdapter(this);
        mGv.setAdapter(mAdapter);
        mAdapter.setOnItemDeleateListener(new ProductfeeGridAdapter.OnItemDeleateListener() {
            @Override
            public void onDelete(String path) {
                mPresenter.deletePic(path);
            }
        });
        mEtcpmc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtcpmc.setCursorVisible(true);
            }
        });
    }

    private void initEvent() {
        mLlfile.setOnClickListener(this);
        mLlgallery.setOnClickListener(this);
        mLlcamera.setOnClickListener(this);
        mBtconfirm.setOnClickListener(this);
        mBtconfirm.setClickable(false); //刚开始不允许有点击事件
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 初始化产品名称 给一个默认值
     */
    private void initProductName() {
        mProductNumber = Control.getProductNumber();
        mEtcpmc.setText("产品" + mProductNumber);
        int length = mEtcpmc.getText().toString().trim().length();
        mEtcpmc.setSelection(length);
    }

    /**
     * 初始化imagepicker
     */
    private void initImagePicker() {
        mImagePicker = ImagePicker.getInstance();
        mImagePicker.setImageLoader(new GlideImageLoader());
        mImagePicker.setMultiMode(true);
        mImagePicker.setShowCamera(false);
        mImagePicker.setSelectLimit(PIC_NUM);
        mImagePicker.setCrop(false);
    }

    /**
     * 显示选择的文件名称
     *
     * @param name 文件名
     */
    private void showFileName(String name) {
        mTv_filename.setText(name);
        mTv_filename.getViewTreeObserver().addOnGlobalLayoutListener(new OnBBfilenameLayoutListener(mTv_filename));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.uploadproductfee_file_ll: //选择文档
                toselectFile(); //文档
                break;
            case R.id.uploadproductfee_gallery_ll: //选择照片
                toGallery();
                break;
            case R.id.uploadproductfee_camera_ll: //拍照
                PermissionUtil.getInstance().requestPermission(this, PermissionUtil.Permission.CAMERA, getString(R.string.camera_permission), getString(R.string.camera_permission_hint), new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        if (mZipImageList.size() >= PIC_NUM) {
                            showToast("最多选择" + PIC_NUM + "张图片");
                        } else {
                            mImagePicker.takePicture(UploadProductfeerateActivity.this, SELECT_CAMERA_REQ);
                        }
                    }

                    @Override
                    public void onDenied() {

                    }
                });
                break;
            case R.id.uploadproductfee_upload_tv: //确定上传
                checkNet();
                break;
        }
    }

    /**
     * 检查是否是流量
     */
    private void checkNet() {
        if (NetUtil.isDataNet()) {
            showWifiTips();
        } else {
            toUploadFileOrImage();
        }
    }

    /**
     * 上传文件或者图片
     */
    private void toUploadFileOrImage() {
        if (TextUtils.isEmpty(mFilePath)) {
            if (mZipImageList.size() > 0) {
                Map<String, File> filemap = new LinkedHashMap<>();
                for (String zipPath : mZipImageList) {
                    if (!TextUtils.isEmpty(zipPath)) {
                        PrintLog.d(TAG, "zipPath:" + zipPath);
                        File file = new File(zipPath);
                        String fileName = file.getName();
                        filemap.put(fileName, file);
                    }
                }
                toUploadFile(filemap);
            } else {
                showToast("请选择正确的文件或者照片");
            }
        } else {
            Map<String, File> filemap = new HashMap<>();
            File file = new File(mFilePath);
            filemap.put(file.getName(), file);
            toUploadFile(filemap);
        }
    }


    /**
     * 去相册选择图片
     */
    private void toGallery() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, mImageList);
        startActivityForResult(intent, SELECT_GALLERY_REQ);
    }

    private void toselectFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");  //用file的话 华为mate8 不能选sd卡的文件
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_FILE_REQ);
    }


    @Override
    public void showImages(List<String> list) {
        mZipImageList.clear();
        mZipImageList.addAll(list);
        if (list.size() > 0) {
            mGv.setVisibility(View.VISIBLE);
            mAdapter.setData(list);
            setDocumentEnable(false, false);
            setConfrimButton(true);
        } else {
            resetStatus();
        }
        mTvytj.setText("已添加（" + list.size() + "）");
    }

    @Override
    public void showFile(String filepath) {
        setConfrimButton(true);
        setDocumentEnable(true, false);
        mFilePath = filepath;
        File tempFile = new File(filepath.trim());
        String fileName = tempFile.getName();
        mRlfile.setVisibility(View.VISIBLE);
        mTv_filename.setVisibility(View.VISIBLE);
        showFileName(fileName);
        mTvytj.setText("已添加（1）");
    }

    @Override
    public void resetImageItemList(ArrayList<ImageItem> list) {
        mImageList.clear();
        mImageList.addAll(list);
    }


    /**
     * 上传本地文件
     *
     * @param filemap 文件地址集合
     */
    private void toUploadFile(Map<String, File> filemap) {
        mSuccessFlag = true;
        if (TextUtils.isEmpty(mEtcpmc.getText())) {
            showToast("产品名称不能为空");
            return;
        } else {
            mUploadProductname = mEtcpmc.getText().toString().trim();
        }
        Map<String, String> params = new HashMap<>();
        params.put("customPath", "appratecollect");
        params.put("productname", mUploadProductname);
        params.put("cardno", UserInfor.getInstance().getUsersfzh());
        params.put("userid", UserInfor.getInstance().getUserid());
        final View uploadingview = View.inflate(mContext, R.layout.dialog_productfee_upload, null);
        final TextView tv_progress = (TextView) uploadingview.findViewById(R.id.dialog_productfee_progress);
        final Dialog progressDialog = ProductfeeDialogHelper.getInstance().createProgressDialog(mContext, uploadingview, 270, 144);
        final Dialog successDialog = ProductfeeDialogHelper.getInstance().createSuccessDialog(mContext);
        final Dialog failDialog = ProductfeeDialogHelper.getInstance().createFailDialog(mContext);

        String appVersion = LoadDataManager.getInstance().getAppVersion();
        String token = LoadDataManager.getInstance().getToken();
        String byjkuuid = LoadDataManager.getInstance().getBYJKUUID();

        BBOkHttp.getInstance(this,appVersion,token,byjkuuid)
                .upload(UrlConstants.BaseUrl + "bbt_rate_fileUpload/query", params, filemap, new IResponseHandler() {
            @Override
            public void onFailure(int statusCode, String error_msg) {
                progressDialog.dismiss();
                failDialog.show();
                toCountdownDismiss(false);
                mProgress = -1;
            }

            @Override
            public void onProgress(long currentBytes, long totalBytes) {
                PrintLog.d(TAG, "currentBytes:" + currentBytes);
                PrintLog.d(TAG, "totalBytes:" + totalBytes);
                int nowProgress = (int) ((100 * currentBytes) / totalBytes);
                if (nowProgress > mProgress) {
                    if (currentBytes == totalBytes) {
                        if(mSuccessFlag){  //防止多次返回成功
                            tv_progress.setText("100%");
                            mProgress = -1;
                            delayShowSucc(progressDialog, successDialog);
                            mSuccessFlag = false;
                        }
                    } else {
                        progressDialog.show();
                        tv_progress.setText(nowProgress + "%");
                        mProgress = nowProgress;
                    }

                }
            }
        });
    }

    /**
     * 延时显示100%的弹窗
     */
    private void delayShowSucc(final Dialog progressDialog, final Dialog successDialog) {
        Disposable subscribe = Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        progressDialog.dismiss();
                        successDialog.show();
                        toCountdownDismiss(true);
                    }
                });
        mRxmanager.addDisposable(subscribe);
    }

    /**
     * 定时让dialog消失
     *
     * @param issuccess ture:上传成功 ,false:上传失败
     */
    private void toCountdownDismiss(final boolean issuccess) {
        int delaytime = 0;
        if(issuccess){
            delaytime = 1000;   //上传失败给的提示时间长一些
        }else{
            delaytime = 2500;  //上传成功
        }
        Disposable subscribe = Observable.timer(delaytime, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (issuccess) { //如果是上传成功的弹窗  那么文件名增加
                            mProductNumber++;  //如果产品名称
                            Control.setProductNumber(mProductNumber);
                            resetStatus();
                            ProductfeeDialogHelper.getInstance().dismissSuccessDialog();
                        } else {
                            ProductfeeDialogHelper.getInstance().dismissFailDialog();
                        }
                    }
                });
        mRxmanager.addDisposable(subscribe);
    }

    /**
     * 设置文档是否可以点击
     *
     * @param enable    ture文档可以点击并且照片图片不能点击
     * @param allenable 是否全部都可以点击
     */
    private void setDocumentEnable(boolean enable, boolean allenable) {
        if (allenable) {
            mIvfile.setImageResource(R.drawable.ic_file_file_enable);
            mIvgallery.setImageResource(R.drawable.ic_file_pic_enable);
            mIvcamera.setImageResource(R.drawable.ic_file_shoot_enable);
            mLlfile.setClickable(true);
            mLlgallery.setClickable(true);
            mLlcamera.setClickable(true);
            mTvwd.setTextColor(Color.parseColor("#4c4c4c"));
            mTvzp.setTextColor(Color.parseColor("#4c4c4c"));
            mTvpz.setTextColor(Color.parseColor("#4c4c4c"));
        } else {
            if (enable) {
                mIvfile.setImageResource(R.drawable.ic_file_file_enable);
                mIvgallery.setImageResource(R.drawable.ic_file_pic_disable);
                mIvcamera.setImageResource(R.drawable.ic_file_shoot_disable);
                mLlfile.setClickable(true);
                mLlgallery.setClickable(false);
                mLlcamera.setClickable(false);
                mTvwd.setTextColor(Color.parseColor("#4c4c4c"));
                mTvzp.setTextColor(Color.parseColor("#804c4c4c"));
                mTvpz.setTextColor(Color.parseColor("#804c4c4c"));
            } else {
                mIvfile.setImageResource(R.drawable.ic_file_file_disable);
                mIvgallery.setImageResource(R.drawable.ic_file_pic_enable);
                mIvcamera.setImageResource(R.drawable.ic_file_shoot_enable);
                mLlfile.setClickable(false);
                mLlgallery.setClickable(true);
                mLlcamera.setClickable(true);
                mTvwd.setTextColor(Color.parseColor("#804c4c4c"));
                mTvzp.setTextColor(Color.parseColor("#4c4c4c"));
                mTvpz.setTextColor(Color.parseColor("#4c4c4c"));
            }
        }

    }

    /**
     * 重置为最初状态
     */
    private void resetStatus() {
        setConfrimButton(false);
        setDocumentEnable(true, true);
        mFilePath = "";
        mRlfile.setVisibility(View.GONE);
        initProductName();
        //照片相关
        mZipImageList.clear();
        mAdapter.setData(mZipImageList);
        mGv.setVisibility(View.GONE);
        mTvytj.setText("已添加（0）");
        mImageList.clear();
        mEtcpmc.setCursorVisible(false);
    }

    /**
     * 设置 确定上传按钮 是否能点击
     *
     * @param isClickable 是否能点击上传按钮
     */
    private void setConfrimButton(boolean isClickable) {
        if (isClickable) {
            mBtconfirm.setTextColor(Color.parseColor("#FFFFFF"));
            mBtconfirm.setBackgroundColor(Color.parseColor("#FA9E00"));
            mBtconfirm.setClickable(true);
        } else {
            mBtconfirm.setTextColor(Color.parseColor("#51000000"));
            mBtconfirm.setBackgroundColor(Color.parseColor("#D9D9D9"));
            mBtconfirm.setClickable(false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECT_FILE_REQ: //文件选择
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    mPresenter.selectFile(this, uri);
                }
                break;
            case SELECT_GALLERY_REQ: //选择相册
                if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
                    if (data != null) {
                        mImageList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        mPresenter.selectGalleryPic(mImageList);
                    } else {
                        showToast("没有数据");
                    }
                }
                break;
            case SELECT_CAMERA_REQ:
                if (resultCode == RESULT_OK) {
                    //发送广播通知图片增加了
                    ImagePicker.galleryAddPic(this, mImagePicker.getTakeImageFile());
                    ImageItem imageItem = new ImageItem();
                    String path = mImagePicker.getTakeImageFile().getAbsolutePath();
                    imageItem.path = path;
                    imageItem.isTakePhoto = true;
                    mImageList.add(imageItem);
                    mPresenter.selectGalleryPic(mImageList);
                    break;
                }
        }
    }

    /**
     * 流量上传的提示框
     */
    private void showWifiTips() {
        View view = View.inflate(mContext, R.layout.dialog_uploadfee_bundlnumber, null);
        DialogUtil.getInstance().creatAlertDialog(mContext, view, 266, 171);
        TextView tv_cancel = (TextView) view.findViewById(R.id.text_cancle);
        TextView tv_confirm = (TextView) view.findViewById(R.id.text_confirm);
        TextView tv_msg = (TextView) view.findViewById(R.id.text_);
        tv_cancel.setText(AppUtil.getString(R.string.fee_wifi_cancel));
        tv_confirm.setText(AppUtil.getString(R.string.fee_wifi_confirm));
        tv_msg.setText(AppUtil.getString(R.string.fee_wifi_msg));
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dismiss();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toUploadFileOrImage();
                DialogUtil.getInstance().dismiss();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


}
